﻿using GameProtocol.Protocol;
using NetCommon;
using RPGGameServer.Logic;
using ServerFrame;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RPGGameServer
{
    /// <summary>
    /// 消息处理中心
    /// </summary>
    class HandlerCenter : AbsHandlerCenter
    {
        //private IHandler login = new LoginHandler();
        /// <summary>
        /// 存储各个逻辑处理模块<模块类型， 模块>
        /// </summary>
        private Dictionary<Protocal, IHandler> dicHandlers = new Dictionary<Protocal, IHandler>();
        /// <summary>
        /// 按照模块类型 添加逻辑模块
        /// </summary>
        /// <typeparam name="T"></typeparam>
        private void AddHandler<T>() where T: IHandler, new()
        {
            T handler = new T();
            if (dicHandlers.ContainsKey(handler.Protocal))
            {
                return;
            }
            dicHandlers.Add(handler.Protocal, handler);
        }
        private IHandler GetHandler(Protocal protocal)
        {
            if (dicHandlers.ContainsKey(protocal))
            {
                return dicHandlers[protocal];
            }
            return null;
        }

        public HandlerCenter()
        {
            AddHandler<LoginHandler>();
        }

        public override void ClientAccept(UserToken token)
        {
            Console.WriteLine("消息处理中心，有客户端接入");
        }

        public override void ClientClose(UserToken token, string error)
        {
            Console.WriteLine("消息处理中心，有客户端离开，原因：" + error);
        }

        public override void ReceiveMessage(UserToken token, object message)
        {
            Console.WriteLine("消息处理中心，有接收到客户端发来的消息" + message.ToString());

            NetModel model = (NetModel)message;

            //把收到的客户端消息派发到指定模块
            IHandler handler = GetHandler(model.protocal);
            if (handler == null)
            {
                return;
            }

            handler.ReceiveMessage(token, model);

        }
    }
}
